package core.android.tools;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;

import java.util.Stack;

/**
 * @作者: XQ
 * @创建时间：2016/7/29 15:53
 * @类说明: activity管理类3..0
 */
public enum AKActivityUtil {
    INSTANCE;

    private Application application;//基础的Application,必须设置
    private final Stack<Activity> activityStack = new Stack<>();

    private final Object OBJ_LOCK = new Object();

    /**
     * key=activity.getClass().getName()
     * value= activity
     */
    public void add(Activity activity) {
        synchronized (OBJ_LOCK) {
            activityStack.add(activity);
        }
    }

    public Activity getTop() {
        Activity activity = null;
        synchronized (OBJ_LOCK) {
            if (!activityStack.isEmpty()) {
                activity = activityStack.peek();
            }
        }
        return activity;
    }


    /**
     * 移除最新加入的Activity
     */
    public void removeTop() {
        synchronized (OBJ_LOCK) {
            if (!activityStack.isEmpty()) {
                activityStack.pop();
            }
        }
    }

    /**
     * 仅从actviityMap中移除Activity对象
     *
     * @param activity
     */
    public void remove(Activity activity) {
        synchronized (activityStack) {
            if (!activityStack.isEmpty()) {
                activityStack.remove(activity);
            }
        }
    }

    /**
     * 结束最新加入的Activity
     */
    public void finish() {
        synchronized (OBJ_LOCK) {
            if (!activityStack.isEmpty()) {
                Activity activity = activityStack.pop();
                activity.finish();
            }
        }
    }

    /**
     * 移除结束Activit
     *
     * @param activity
     */
    public void finish(Activity activity) {
        if (activity != null) {
            synchronized (OBJ_LOCK) {
                if (!activityStack.isEmpty()) {
                    activityStack.remove(activity);
                }
            }
            activity.finish();
        }
    }

    public void finishAll() {
        synchronized (OBJ_LOCK) {
            for (Activity activity : activityStack) {
                if (activity != null) {
                    activity.finish();
                }
            }
            activityStack.clear();
        }

    }


    public Application getApplication() {
        return application;
    }

    public void setApplication(Application application) {
        this.application = application;
    }

    /**
     * 使用application即可跳转,跳转只需包名即可
     *
     * @param cls
     */
    public void jump(Class cls) {
        if (application == null) {
            AK.e("application is null!");
            return;
        }

        Intent intent = new Intent(application, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        application.startActivity(intent);
    }
}
